<template>
	<view>
		<u-upload
			v-if="!isVideo"
			ref="uUpload"
			:action="action"
			:form-data="formData"
			:header="header"
			@click="addClick()"
			@on-uploaded="onUploaded"
			@on-error="onError"
			@on-success="onSuccess"
			@on-remove="onRemove"
			:file-list="fileList"
			:size-type="sizeType"
			:show-tips="false"
			:auto-upload="false"
			:custom-btn="hasVideo"
			:max-count="maxCount">
		</u-upload>
		<view v-else class="video-view">
			<video
				class="video"
				id="myVideo"
				:src="videoPath"
				autoplay="true"
			/>
			<u-icon @click="delClick" class="video-del" size="50" name="minus-circle-fill"></u-icon>
			<u-icon @click="playClick" class="video-play" size="80" name="play-circle-fill"></u-icon>
		</view>
		<u-action-sheet :list="list" v-model="show" @click="uploadTypeClick"></u-action-sheet>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import { http } from '@/api/service.js'
	import { wrapVideoSnapshot } from '@/utils/utils'
	export default {
		name:"XUpload",
		props: {
			formData: {
				type: Object,
				default () {
					return {
						'bizType': 'xybaby365'
					}
				}
			},
			hasVideo: {
				type: Boolean,
				default () {
					return false
				}
			},
			maxCount: {
				type: Number,
				default () {
					return 9
				}
			}
		},
		data() {
			return {
				fileList: [],
				action: '',
				header: {
					ticket: '',
				},
				
				list: [{
					text: '照片',
				}, {
					text: '视频'
				}],
				show: false,
				sizeType: ['compressed'],
				isVideo: false,
				
				//图片列表
				lists: [],
				videoUrl: '',
				videoPath: '',
			};
		},
		computed: {
			...mapState({
				appType: state => state.app.appType
			})
		},
		onReady() {
			this.videoContext = uni.createVideoContext('myVideo')
		},
		created() {
			if (this.appType === 'app-tch' || this.appType === 'mp-tch') {
				this.action = `${http.config.baseURL}pad/upload/file`;
			} else {
				this.action = `${http.config.baseURL}wx/api/upload/file`;
			}
			this.header.ticket = uni.getStorageSync('ticket');
		},
		methods: {
			upload() {
				if (this.isVideo) {
					this.uploadVideo(this.videoPath);
				} else {
					this.$refs.uUpload.upload();
				}
			},
			addClick() {
				if (this.lists.length === 0) {
					this.show = true;
				} else {
					this.$refs.uUpload.selectFile();
				}
			},
			
			uploadTypeClick(index) {
				if (index === 0) {
					this.$refs.uUpload.selectFile();
				} else {
					this.chooseVideo();
				}
			},
			
			chooseVideo() {
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					success: res => {
						console.log(res);
						this.videoPath = res.tempFilePath;
						this.isVideo = true;
					}
				});
			},
			
			onUploaded(lists, name) {
				const flag = lists && lists[0] && lists[0].response ? true : false;
				let resourceUrl = null;
				if(flag) {
					let errCode = '000000'
					resourceUrl = lists.map(x => {
						
					  if (x.response && x.response.code !== '000000') {
							errCode = x.response.code;
						}
						return x.response ? x.response.data : x.url; // 确保返回一个值，即使 response 为空
					}).join('|');
					if (errCode !== '000000') {
						uni.hideLoading()
						this.$u.toast('图片包含不适合发布的内容，请重新选择照片');
						return
					}
				}else {
					resourceUrl = lists.map(x => {
						return x.url;
					}).join('|');
				}
				
				
				

				this.$emit('onUploaded', {
						resourceUrl: resourceUrl,
						mediaType: 1
					},
				);
			},
			onRemove(index, lists, name) {
				let resourceUrl = lists.map(x => {
					// return x.url;
					return x.response.data ? x.response.data : x.url;
				}).join('|');
				this.$emit('onRemove', {
						resourceUrl: resourceUrl,
						mediaType: 1
					},
				);
			},
			
			onSuccess(data, index, lists, name) {
				console.log(data, index, lists, name,'data, index, lists, name');
				// uni.showLoading()
			},
			
			onError(res, index, lists, name) {
				console.log(res);
				uni.hideLoading();
				this.$u.toast('图片上传失败');
			},
			
			onListChange (lists, name) {
				this.lists = lists;
			},
			
			uploadVideo(path) {
				uni.showLoading({})
				uni.uploadFile({
					url: this.action,
					name: 'file',
					filePath: path,
					formData: this.formData,
					header: this.header,
					success: res => {
						console.log(res)
						const data = this.toJson && this.$u.test.jsonString(res.data) ? JSON.parse(res.data) : res.data;
						if (![200, 201, 204].includes(res.statusCode)) {
							this.$u.toast('视频上传失败1');
						} else {
							// 上传成功
							const json = JSON.parse(data);
							console.log(json);
							this.$emit('onUploaded', {
									resourceUrl: json.data,
									mediaType: 2
								},
							);
						}
					},
					fail: e => {
						console.log(e);
						this.$u.toast('视频上传失败2');
					},
					complete: res => {
						uni.hideLoading();
					}
				})
			},
			
			playClick() {
				console.log('play');
				this.videoShow = true;
			},
			
			delClick() {
				this.isVideo = false;
			},
			
			wrapSnapshot(url) {
				return wrapVideoSnapshot(url);
			},
			
			videoClose() {
				this.videoContext.stop()
			},
		},
	}
</script>

<style lang="scss">
	.video-view{
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		.video {
			align-self: center;
			width: 640rpx;
			height: 360rpx;
		}
		.video-del{
			position: absolute;
			top: 10rpx;
			right: 10rpx;
		}
		
		.video-play{
			position: absolute;
		}
	}
</style>
